﻿namespace EyeOpen.Crypt.ViewModel.Silverlight
{
    using System;
    using System.Windows;
    using System.Windows.Input;
    using EyeOpen.Crypt.Client.Service;
    using EyeOpen.ViewModel.Silverlight;

    public partial class CryptViewModel : ViewModelBase
    {
        public ICommand EncryptDecryptCommand
        {
            get;
            private set;
        }

        public ICommand CopyToClipboadCommand
        {
            get;
            private set;
        }

        private void ExecuteCryptDecrypt()
        {
            ErrorMessage = string.Empty;
            IsBusy = true;
            EncryptInfoIsAvailable = false;
            proxy.CryptDecrypt(Password, CryptText);
        }

        private void CryptDecryptLoaded(object sender, CryptEventArgs e)
        {
            CryptText = e.Result.Text;
            EncryptionType = e.Result.EncryptionType;
            ClearTextLenght = e.Result.ClearTextLenght;
            EncryptedTextLenght = e.Result.EncryptedTextLenght;
            CompressedTextLenght = e.Result.CompressedTextLenght;

            if (e.Result.HasError)
            {
                var exception = e.Result.Error;

                while (exception != null)
                {
                    ErrorMessage += exception + Environment.NewLine;
                    ErrorShower.ShowErrors();
                }
            }

            IsBusy = false;
            EncryptInfoIsAvailable = true;
        }

        private void ExecuteCopyToClipboard()
        {
            if (!string.IsNullOrEmpty(CryptText))
            {
                Clipboard.SetText(CryptText);
                MessageBox.Show("Encrypted text copied to clipboard.");
            }
        }

        private void NotifyErrorsChanged(string propertyName)
        {
            OnErrorsChanged(propertyName);
        }
    }
}